package marek.barak.classes;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

public class ConnectionActions {
	private static ConnectionActions instance;
	private final File aLocation;
	
	private ConnectionActions(){
		aLocation = new File(".",File.separator+"Actions");
		if(!aLocation.exists())
			aLocation.mkdir();
	}
	public static ConnectionActions getInstance(){
		if(instance==null)
			instance = new ConnectionActions();
		return instance;
	}
	
	@SuppressWarnings("unchecked")
	public List<Action> loadAllActions() throws FileNotFoundException, IOException, ClassNotFoundException{
		List<Action> actions = null;
		if( (new File(aLocation+File.separator+"actions.dt")).exists()){
			ObjectInputStream in = null;
			try{
				in = new ObjectInputStream(new FileInputStream(aLocation.getAbsolutePath()+File.separator+"actions.dt"));
				actions = (ArrayList<Action>) in.readObject();
				System.out.println("Read sucessfull");
			}finally{
				if(in!=null)
					in.close();
			}
			
		}else
			actions = new ArrayList<Action>();
		
		return actions;
	}
	public void saveAllActions(List<Action> actions) throws FileNotFoundException, IOException{
		ObjectOutputStream out = null;
		try{
			out = new ObjectOutputStream(new FileOutputStream(aLocation.getAbsolutePath()+File.separator+"actions.dt"));
			out.writeObject(actions);
			System.out.println("Saved");
		}finally{
			if(out!=null)
				out.close();
		}
		
	}
}
